<?php

namespace IDock\Insurance\AICS\Response;

use IDock\Http\Response;
use IDock\Insurance\AICS\Response\AllAICSResponse;
use IDock\Printer\EPolicyDownloadPrinter;
use IDock\Printer\ProposalRecallPrinter;

class EPolicyDownloadResponse extends AllAICSResponse
{
    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = str_replace('&lt;','<',$body);
        $body = str_replace('&gt;','>',$body);
        $body = str_replace("'",'"',$body);
        $start = strpos($body,'<response>');
        $end = strpos($body,'</response>');
        $body = substr($body,$start + 10,intval($end - $start -10));

        if ($body) {
            libxml_disable_entity_loader(false);
            $body = simplexml_load_string($body);
            $body = $this->objectToArray($body);
            $errorCode = $body['head']['responseCompleteMessageStatus']['messageStatusCode'] ?? '';
            $message = $body['head']['responseCompleteMessageStatus']['messageStatusDescription'] ?? '未知错误';
            $this->setBody($body);
            if ($errorCode !== 'E0000') {
                $this->setError($message);
                return $this;
            }
        }

        return $this;
    }

    public function printerInit(): Response
    {
        $data = $this->getBody();
        $jqUrl = $data['jqpolicyUrl'] ?? '';
        $syUrl = $data['sypolicyUrl'] ?? '';
        $ywUrl = $data['ywpolicUrl'] ?? '';
        $signUrl = $data['policyBZUrl'] ?? '';

        if ($signUrl) {
            $signUrl = str_replace(['amp;'],'',$signUrl);
        }

        $url = $jqUrl ?: $syUrl;
        if($ywUrl){
            $url = $ywUrl;
        }
        //去除多余的转义符
        $url = str_replace(['amp;'],'',$url);
        $proposalRecallPrinter = new EPolicyDownloadPrinter();
        $proposalRecallPrinter->finish = true;
        $proposalRecallPrinter->doing = false;
        $proposalRecallPrinter->url = $url;
        $proposalRecallPrinter->signUrl = $signUrl;
        $this->printer = $proposalRecallPrinter;
        return  $this;
    }
}
